﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using DialoguerEditor;
using System.IO;
using System.Text.RegularExpressions;

public class DialoguerEnumGenerator : EditorWindow {

	[MenuItem("Tools/Dialoguer/Generate Dialogues Enum", false, 1000)]
	//[MenuItem("Dialoguer/Generate Dialogues Enum", false, 1000)]
	//[MenuItem("Assets/Dialoguer/Generate Dialogues Enum", false, 1000)]
	static public void GenerateDialoguesEnum(){
		checkDialoguerResourcesFolder();

		List<string> lines = new List<string>();
		lines.Add("// This enum was generated by Dialoguer");
		lines.Add ("//\tDo not modify this file, it will be overwritten by Dialoguer.");
		lines.Add("public enum DialoguerDialogues{");
		List<DialogueEditorDialogueObject> dialogues = DialogueEditorDataManager.data.dialogues;
		for(int i = 0; i<dialogues.Count; i+=1){

			if(dialogues[i].name == ""){
				continue;
			}

			bool skip = false;

			for(int ii = 0; ii<i; ii++){
				if(dialogues[i].name == dialogues[ii].name){
					Debug.LogWarning("Dialogue " + i + ": '"+dialogues[i].name+"' has a name that is already in use. Skipping. Please rename this dialogue.");
					skip = true;
				}
			}

			if(skip){continue;}

			//Debug.Log("Adding " + dialogues[i].name);

			string varName = dialogues[i].name.Replace(' ', '_');
			varName = Regex.Replace(varName, @"[^a-zA-Z0-9\_]+", "");

			lines.Add("\t"+varName+" = "+i+",");
		}
		lines.Add("}");

		AssetDatabase.DeleteAsset(DialogueEditorFileStatics.ENUMS_PATH + DialogueEditorFileStatics.DIALOGUE_ENUMS_FILENAME);
		File.WriteAllLines(@DialogueEditorFileStatics.ENUMS_PATH + DialogueEditorFileStatics.DIALOGUE_ENUMS_FILENAME, lines.ToArray());
		AssetDatabase.Refresh();
	}

	private static void checkDialoguerResourcesFolder(){
		bool outputFolderExists = System.IO.Directory.Exists(@DialogueEditorFileStatics.ASSETS_FOLDER_PATH+"/"+DialogueEditorFileStatics.OUTPUT_FOLDER_PATH);
		if(!outputFolderExists) AssetDatabase.CreateFolder(DialogueEditorFileStatics.ASSETS_FOLDER_PATH, DialogueEditorFileStatics.OUTPUT_FOLDER_PATH);
		bool enumsFolderExists = System.IO.Directory.Exists(@DialogueEditorFileStatics.ASSETS_FOLDER_PATH+"/"+DialogueEditorFileStatics.OUTPUT_FOLDER_PATH+"/"+DialogueEditorFileStatics.OUTPUT_ENUMS_FOLDER_PATH);
		if(!enumsFolderExists) AssetDatabase.CreateFolder(DialogueEditorFileStatics.ASSETS_FOLDER_PATH+"/"+DialogueEditorFileStatics.OUTPUT_FOLDER_PATH, DialogueEditorFileStatics.OUTPUT_ENUMS_FOLDER_PATH);
	}
}
